<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use addons\third\model\Third;
use \app\admin\model\IncomeDetail;
/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{
    
    /**
     * Order模型对象
     * @var \app\admin\model\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Order;
        $this->view->assign("payStatusList", $this->model->getPayStatusList());
        $this->view->assign("orderStatusList", $this->model->getOrderStatusList());
        $this->view->assign("specTypeList", $this->model->getSpecTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }

            /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);

        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with('user')
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with('user')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            // halt($list);
            $list = collection($list)->toArray();
            foreach ($list as $key => $value) {
                if(empty($value['goods_name'])){
                    $shoppingcar_array = json_decode($value['shoppingcar_id'],true);
                    $goods_list = Db::name('shoppingcar')->where('id','in',$shoppingcar_array)->select();
                    $list[$key]['goods_list'] = $goods_list;
                }
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }
    public function randomkeys($length){
        $info="";
        $pattern = '1234567890abcdefghijklmnopqrstuvwxyz';
        for($i=0;$i<$length;$i++) {
            $info .= $pattern{mt_rand(0,35)};    //生成php随机数
        }
            return $info;
    }
    public function bank(){

        $id = input('ids');//这个是提现明细表的id
        $income_detail =  IncomeDetail::get($id);

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            $res = Db::name('income_detail')->where(['id'=>$params['id']])->update(['watch'=>$params['watch']]);
            if($res)$this->success('修改成功');
        }

        $income_detail = $income_detail->toArray();

        $bank_data = Db::name('user')->field('bank_name,card_number,account_bank,id_num,bank_phone')->where(['id'=>$income_detail['user_id']])->find();

        $list = array_merge($income_detail,$bank_data);
        $this->view->assign("data", $list);
        return $this->view->fetch();
    }

    public function fahuo(){

        $order_id = input('ids');
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            $order_detail = Db::name('order')->where(['id'=>$params['id']])->find();
            if($order_detail['code'])$this->error('提货码已经存在');

            if($order_detail['order_status']=='10')$this->error('该订单未支付');

            $params['delivery_time'] = time();
            $params['order_status'] = 30;
            // 订单状态:10=未支付,20=已支付待发货,30=已发货,40=确认收货 
            $params['code'] = self::randomkeys(6);

            $third = Third::where(['user_id' => $order_detail['user_id'], 'platform' => 'wxapp'])->find();
            $send_data['template_id'] = 'r09nlCRmP-bH2Lo-MojbAGsogF8Zgl-_5VmO8MdN6iE';
            $send_data["touser"] = $third['openid'];
            $send_data['data'] = [
                'time3'=>[
                  'value' => date('Y年m月d日 H:i:s',time())
                ],
                'thing1' =>[
                  'value' => '提货码是'.$params['code']
                ],
                'phrase2' =>[
                  'value' => '通过'
                ],
            ];

            $send_data['page'] = '?need_id=';//点击链接跳转的地址

            // $res = $this->sendSubMessage($send_data,$this->getAccessToken());
            // $res = json_decode($res,true);
            $up_res = Db::name('order')->update($params);
            if($up_res)$this->success('发货成功');  
            if($res['errmsg']=='ok'){
                $up_res = Db::name('order')->update($params);
                   if($up_res)$this->success('发货成功');                 
            }else{
                $this->error($res['errmsg']);
            }
        }

        $list = $this->model
            ->with('user')
            ->find($order_id);

        $list = $list->toArray();
        $list['address'] = Db::name('region')->where('id',$list['region_id'])->find();

        if(empty($list['goods_name'])){
            $shoppingcar_array = json_decode($list['shoppingcar_id'],true);
            $goods_list = Db::name('shoppingcar')->where('id','in',$shoppingcar_array)->select();
            $list['goods_list'] = $goods_list;
        }
        // halt($list);
        $this->view->assign("order_id", $order_id);
        $this->view->assign("data", $list);
        return $this->view->fetch();
    }
    protected function sendSubMessage($params,$token){
        $url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token='.$token;
        $re = $this->curl_url($url,$params);
        return $re;
    }
    protected function curl_url($url, $json)
    { 
        $body = json_encode($json);
        // return $body;
        $headers = array("Content-type: application/json;charset=UTF-8", "Accept: application/json", "Cache-Control: no-cache", "Pragma: no-cache");

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $result = curl_exec($ch);
        curl_close($ch);

        return $result;
    }
    protected function getAccessToken()
    {
      //当前时间戳
      $now_time = time();

      //失效时间
      $timeout = 7200 ;

      //判断access_token是否过期
      $before_time = $now_time - $timeout;

      //未查找到就为过期
      $access_token = Db::name('access_token')
        ->where('createtime' ,'>',$before_time)
        ->value('access_token');

      if(empty($access_token)){
        $config = get_addon_config('epay');

        $appId= $config['wechat']['miniapp_id'];// 小程序 APPID
        $appSecret = $config['wechat']['app_secret'];//小程序密钥
        $r = file_get_contents("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appId&secret=$appSecret"); //返回的是字符串，需要用json_decode转换成数组
        $data = json_decode($r,true);
        Db::name('access_token')->insert(['access_token'=>$data['access_token'],'createtime'=>$now_time]);
        return $data['access_token'];
      }
      return $access_token;
      
    }
    

}
